package leetcode.l3;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.IntConsumer;

/**
 * 打印0与奇偶数
 * 相同的一个 ZeroEvenOdd 类实例将会传递给三个不同的线程：
 * <p>
 * 线程 A 将调用 zero()，它只输出 0 。
 * 线程 B 将调用 even()，它只输出偶数。
 * 线程 C 将调用 odd()，它只输出奇数。
 * 每个线程都有一个 printNumber 方法来输出一个整数。请修改给出的代码以输出整数序列 010203040506... ，其中序列的长度必须为 2n。
 * <p>
 * 使用信号量的解法
 * countDownLatch思路与使用信号量是一样的
 *
 * @author LiYilin on 2020/3/29
 */
public class L3ZeroEvenOddSolution2CountDownLatch {

    private int n;

    private CountDownLatch z = new CountDownLatch(0);
    private CountDownLatch e = new CountDownLatch(1);
    private CountDownLatch o = new CountDownLatch(1);

    public L3ZeroEvenOddSolution2CountDownLatch(int n) {
        this.n = n;
    }

    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            //z初始值是0,await其实第一次不能阻止线程运行
            System.out.println("z await");
            z.await();
            printNumber.accept(0);
            z = new CountDownLatch(1);
            if ((i & 1) == 0) {
                o.countDown();
            } else {
                e.countDown();
            }
        }
    }

    /**
     * 打印偶数
     */
    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 2; i <= n; i += 2) {
            e.await();
            printNumber.accept(i);
            e = new CountDownLatch(1);
            z.countDown();
        }
    }

    /**
     * 打印奇数
     */
    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i += 2) {
            o.await();
            printNumber.accept(i);
            o = new CountDownLatch(1);
            z.countDown();
        }
    }

    public static void main(String[] args) {
        L3ZeroEvenOddSolution2CountDownLatch zeroEvenOdd = new L3ZeroEvenOddSolution2CountDownLatch(5);

        //缺少ThreadFactory的实现
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 10, 3L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));

        executor.execute(() -> {
            try {
                zeroEvenOdd.even(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        executor.execute(() -> {
            try {
                zeroEvenOdd.odd(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        executor.execute(() -> {
            try {
                zeroEvenOdd.zero(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        executor.shutdown();
    }
}
